package com.cg.offer;

import com.cg.leetcode.TreeNode;
import org.junit.Test;

import java.util.*;

/**
 * 剑指Offer 32-III.从上到下打印二叉树III
 *
 * @program: LeetCode->Offer_32_III
 * @description: 剑指Offer 32-III.从上到下打印二叉树III
 * @author: cg
 * @create: 2022-03-14 16:50
 **/
public class Offer_32_III {

    @Test
    public void test32_III() {
        TreeNode root = new TreeNode(3);
        root.left = new TreeNode(9);
        root.right = new TreeNode(20);
        root.right.left = new TreeNode(15);
        root.right.right = new TreeNode(7);
        System.out.println(levelOrder(root));
    }

    /**
     * 请实现一个函数按照之字形顺序打印二叉树，即第一行按照从左到右的顺序打印，第二层按照从右到左的顺序打印，第三行再按照从左到右的顺序打印，其他行以此类推。
     * <p>
     * 例如:
     * 给定二叉树: [3,9,20,null,null,15,7],
     *    3
     *   / \
     *  9  20
     *    /  \
     *   15   7
     * 返回其层次遍历结果：
     * .
     * [
     * [3],
     * [20,9],
     * [15,7]
     * ]
     * <p>
     * 提示：
     * 节点总数 <= 1000
     *
     * @param root
     * @return
     */
    public List<List<Integer>> levelOrder(TreeNode root) {
        if (root == null) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Deque<TreeNode> deque = new ArrayDeque<>();
        deque.addLast(root);
        int lay = 1;
        while (!deque.isEmpty()) {
            List<Integer> row = new ArrayList<>();
            for (int i = deque.size(); i > 0; i--) {
                if ((lay % 2) == 1) {
                    // 奇数层
                    TreeNode node = deque.removeFirst();
                    row.add(node.val);
                    if (node.left != null) {
                        deque.addLast(node.left);
                    }
                    if (node.right != null) {
                        deque.addLast(node.right);
                    }
                } else {
                    // 偶数层
                    TreeNode node = deque.removeLast();
                    row.add(node.val);
                    if (node.right != null) {
                        deque.addFirst(node.right);
                    }
                    if (node.left != null) {
                        deque.addFirst(node.left);
                    }
                }
            }
            lay++;
            res.add(row);
        }
        return res;
    }

}
